xquery version "0.9-ml"

import module namespace cm = "http://marklogic.com/ps/common" at "common.xqy"
import module namespace s="http://www.marklogic.com/ps/lib/lib-session" at "lib-session.xqy"

define function list() {
    let $config := $s:CONFIG
    let $request-element-localname := $config/request-element-localname
    let $request-element-localname := 
      if (fn:exists($request-element-localname)) then
        $request-element-localname
      else
        "request"
    let $request-element-namespace := $config/request-element-namespace
    let $request-element-namespace := 
      if (fn:exists($request-element-namespace)) then
        $request-element-namespace
      else
        ""
    return
	element results {
		for $service in $s:SERVICES
		let $name := fn:data($service/name)
		let $service-request-element-localname := 
		  if (fn:exists($service/request-element-localname)) then
		    $service/request-element-localname
		  else
		    $request-element-localname
		let $service-request-element-namespace := 
		  if (fn:exists($service/request-element-namespace)) then
		    $service/request-element-namespace
		  else
		    $request-element-namespace 
		return 
		<service>
			<name>{$name}</name>
			<xqueryPath>{fn:data($service/xquery-path)}</xqueryPath>
			<request-element-localname>{fn:data($service-request-element-localname)}</request-element-localname>
			<request-element-namespace>{fn:data($service-request-element-namespace)}</request-element-namespace>
			<queries>
			{
				for $query in s:get-queries($name)
				let $query-name := fn:data($query/@name)
				return 
				<query>
				<name>{$query-name}</name>
				{$query/element()}
				</query>
			}
			</queries>
		</service>
	}
}

xdmp:set-response-content-type("text/xml"),
try
{
    let $request := cm:get-request-element(())
    let $action := $request/element()
    let $log := xdmp:log(xdmp:quote($action))
    return
        typeswitch ($action)
        case element(list) return list()
        default return 
            fn:error(xs:QName("malformed"), 
                concat(
                    "Invalid request type ", 
                    node-name($action), 
                    ". Request is malformed: ", 
                    xdmp:quote($request)
                )
            )
}
catch($e) {
    <error>400 Bad Request {$e}</error>
}


